<template>
    <homeBase @update_patient="update_patient" btn_text="添加病历信息"  >
        <template v-slot:title>
            <p>历史病历详情页</p>
        </template>

        <template v-slot:container>
            <div class="container">
            <div class="patient-info">
            <table class="patient-data" v-if="patient">
               <tr>
                    <td class="key">姓名</td><td colspan="4" class="value" id="name" @blur="td_change1($event)">{{ patient.name }}</td>
                    <td class="key">出生年日</td><td colspan="3" class="value" id="birthday" @blur="td_change1($event)">{{ patient.birthday }}</td><td colspan="1" style="fontSize:10px" v-show="patient.age">年龄：{{ patient.age }}</td>
                </tr>
                <tr>
                    <td class="key">身份证号</td><td colspan="4" class="value" id="card_id" @blur="td_change1($event)">{{ patient.card_id }}</td>
                    <td class="key">手机号码</td><td colspan="4" class="value" id="phone" @blur="td_change1($event)">{{ patient.phone }}</td>
                </tr>
                <tr>
                    <td class="key">最近看病时间</td><td colspan="4" class="value" id="last_time" @blur="td_change1($event)">{{ patient.last_time }}</td>
                    <td class="key">医保类别</td><td colspan="4" class="value" id="medical_insurance" @blur="td_change1($event)">{{ patient.medical_insurance }}</td>
                </tr>
                <tr>
                    <td class="key">目前身体状况</td><td colspan="4" class="value" id="health" @blur="td_change1($event)">{{ patient.health }}</td>
                    <td class="key">性别</td><td colspan="4" class="value" id="gender" @blur="td_change1($event)">{{ patient.gender }}</td>
                </tr>
                <tr>
                    <td colspan="10" style="fontWeight:bolder" >病历</td>
                </tr>
                <!-- <tr v-for="(meide_r,index) in patient.medical_record" :key="index" @click="current_medical_record(meide_r,index)" :class="{select:index==select_medical_record}"> -->
                <tr v-for="(meide_r,index) in patient.medical_record" :key="index" :class="{select1:index==select_medical_record}">
                    <!-- <td colspan="1" class="key value" @blur="td_change($event,index,1)" id="treat_time">{{ meide_r["treat_time"] }}</td> -->
                    <td  colspan="10">
                    <tr class="medical_record">
                        <td colspan="1" style="fontWeight: bolder;">就诊时间:</td><td colspan="4" class="key value" @blur="td_change($event,index,1)" id="treat_time">{{ meide_r["treat_time"] }}</td>
                        <td colspan="1" style="fontWeight: bolder;">病历号</td><td colspan="4" id="id">{{ meide_r.id }}</td>
                    </tr>
                    
                    <tr class="medical_record">
                        <td colspan="1" style="fontWeight: bolder;">就诊医院:</td><td colspan="4" id="treat_hospital" class="value" @blur="td_change($event,index,1)"> {{ meide_r["treat_hospital"] }} </td>
                        <td colspan="1" style="fontWeight: bolder;">就诊医生:</td><td colspan="4" id="docter_name" class="value" @blur="td_change($event,index,1)">{{ meide_r["docter_name"] }}</td>
                        
                    </tr>
                    <tr class="medical_record">
                        <td colspan="1" style="fontWeight: bolder;">症状:</td><td colspan="9" id="symptom_description" class="value" @blur="td_change($event,index,1)"> {{ meide_r["symptom_description"] }} </td>
                    </tr>
                    <tr class="medical_record">
                        <td colspan="1" style="fontWeight: bolder;">用药:</td><td colspan="9" id="use_medicinal" class="value" @blur="td_change($event,index,1)">{{ meide_r["use_medicinal"] }}</td>
                    </tr>
                    <!-- <tr class="medical_record">
                        <td colspan="1" style="fontWeight: bolder;">处方:</td><td colspan="9" @click="change_other($event,index)" id="prescription" class="value" @blur="td_change($event,index,1)">{{ meide_r["prescription"] }}</td>
                    </tr> -->
                    <tr class="medical_record">
                        <td colspan="10" style="fontWeight: bolder;">处方:</td>
                    </tr>
                    <!-- style="magin:0px;padding:0px" -->
                    <tr class="medical_record" >
                        <td style="magin:0px;padding:0px" colspan="10">
                            <textarea readOnly v-model="meide_r['prescription']" class="value" id="prescription" @input="input_content($event)"  @blur="td_change($event,index,1)" name="" cols="10" rows="2">{{ meide_r["prescription"] }}</textarea>
                        </td>
                    </tr>
                    <tr class="medical_record">
                        <td colspan="10" style="fontWeight: bolder;">治疗结果:</td>
                        <!-- <td colspan="9" @click="change_other($event,index)" small id="treatment_results" class="value" @blur="td_change($event,index,1)">{{ meide_r["treatment_results"] }}</td> -->
                    </tr>
                    <tr class="medical_record" >
                        <td colspan="10" style="magin:0px;padding:0px">
                            <textarea readOnly v-model="meide_r['treatment_results']" class="value" id="treatment_results" @input="input_content($event)"  @blur="td_change($event,index,1)" name="" cols="10" rows="2">{{ meide_r["treatment_results"] }}</textarea>
                        </td>
                    </tr>
                    </td>
                </tr>
            </table>
            <div v-show="isShow_pop_up" class="pop_up">
                <div class="header">
                    <div></div>
                    <div class="title">{{ pop_up_title }}</div>
                    <div @click="pop_up_cancel()" class="close">【关闭】</div>
                </div>
                <!-- <div class="drugs"><label for="">请输入药品：</label><input class="ipt" type="text"><button>添加</button></div> -->
                <!-- <textarea readonly v-model="pop_up_content" name="" id="" cols="30" rows="10"></textarea> -->
                <textarea v-model="pop_up_content" name="" id="" cols="30" rows="10"></textarea>
                <div @click="pop_up_ok()" class="ok">确定</div>
            </div>
            <!-- <p v-else class="spare">请输入你要查询的信息</p> -->
            <div class="button" v-if="patient">
                <button class="edit" @click="edit($event)">{{ button_text }}</button>
                <!-- <button v-show="submitShow" class="add_medical_record" @click="add_medical_record">新增病历</button> -->
                <button v-show="submitShow" class="add_medical_record" @click="del_medical_record">删除病历</button>
                <button v-show="submitShow" class="submit" @click="submit">提交</button>
                <button class="back_list" @click="$router.push('/medical_record_list')">返回列表</button>
            </div>
            </div>
            </div>
        </template>
    </homeBase>
</template>

<script>
import homeBase from '@/components/home/homeBase.vue'
export default {
    props:['title'],
    data(){
        return{
            submitShow:false,
            button_text:'编辑信息',
            select_medical_record:null,
            select_medical_record_item:null,
            patient_list:null,
            patient:{
                name:"",
                age:"",
                card_id:"",
                phone:"",
                last_time:"",
                register_n:"",
                health:"",
                medical_record:[],
                treat_record:[]
            },
            new_patient:{},
            del_m_r:[],
            err_msg:"",
            err_msg_show:false,
            isShow_pop_up:false,
            pop_up_id:"",
            pop_up_title:"",
            pop_up_content:"",
            query:null
        }
    },
    components:{
        homeBase
    },
    methods:{
        edit(e){
            let el = document.querySelectorAll(".value")
            if(this.button_text=='编辑信息'){
                this.button_text='取消'
                this.submitShow=!this.submitShow
                el.forEach(item=>{
                    item.setAttribute("contentEditable",this.submitShow)
                    if(item.id == "prescription" || item.id == "treatment_results"){
                        // 更改文本域的属性
                        item.readOnly=!this.submitShow
                        item.style.resize="vertical"
                    };
                })
                el[0].focus()
            }else{
                this.button_text='编辑信息'
                this.submitShow=!this.submitShow
                this.update_patient()
                el.forEach(item=>{
                    item.setAttribute("contentEditable",this.submitShow)
                    if(item.id == "prescription" || item.id == "treatment_results"){
                        // 更改文本域的属性
                        item.readOnly=!this.submitShow
                        item.style.resize="none"
                    };
                })
            }
        },
        input_content(el){
            let e = el.currentTarget
            console.log(e.scrollHeight,e.offsetHeight,e.clientHeight);
            if(e.scrollHeight>e.offsetHeight){
                // let h = e.offsetHeight
                e.style.height=e.scrollHeight+10+"px"
                console.log(e.style.height);
            }
        }
        ,
        add_medical_record(){  // 添加病历
            let time = new Date().toLocaleDateString()  // .replace(/\//g,"-")
            this.patient.medical_record.push({
                "id":"null",
                "patient_id":this.patient["id"],
                "patient_name":this.patient["name"],
                "patient_gender":this.patient["gender"],
                "medical_insurance":this.patient["medical_insurance"],
                "treat_time":time,
                "treat_hospital":"重庆XX医院",
                "docter_name":"",
                "symptom_description":"",
                "prescription":"",
                "use_medicinal":"",
                "treatment_results":""
            })
            
            setTimeout(()=>{
                let el = document.querySelectorAll(".value")
                el.forEach(item=>{
                    item.setAttribute("contentEditable",this.submitShow)
                })
            })
            // let el = document.querySelectorAll(".value")
            // el.forEach(item=>{
            //     item.setAttribute("contentEditable",this.submitShow)
            // })
        },
        del_medical_record(){  // 删除病历
            if(this.select_medical_record==null){
                this.$toast.fail("请先点击要删除的病历")
                return
            }
            let conf = confirm("你确定要删除该信息吗")
            if(!conf){
                console.log("取消编辑");
                return
            }
            let m_id = this.patient.medical_record[this.select_medical_record]["id"]
            let patient_id = this.patient.medical_record[this.select_medical_record]["patient_id"]
            if( m_id != "null"){
                let temp={}
                temp["id"]=m_id
                temp["patient_id"]=patient_id
                temp["table_name"]="medecal_record"
                this.del_m_r.push(temp)

                // let re = new RegExp(`${m_id},?`);
                // console.log(re);
                // this.patient.medical_record_str = this.patient.medical_record_str.replace(re,"")
                // this.patient.medical_record_str = this.patient.medical_record_str.replace(/,$/,"")
                // console.log(this.patient.medical_record_str);
                // console.log(this.del_m_r);
            }
            this.patient.medical_record.splice(this.select_medical_record,1)
            // this.select_medical_record=null

            // this.new_patient.medical_record.splice(this.select_medical_record,1)
            // setTimeout(()=>{
            //     let el = document.querySelectorAll(".value")
            //     el.forEach(item=>{
            //         item.setAttribute("contentEditable",this.submitShow)
            //     })
            // })
            console.log(this.del_m_r);
        },
        current_medical_record(item,index){  // 记录当前选择的病历
            // el.currentTarget.style.backgroundColor="#f1f1f1"
            this.select_medical_record_item = item
            this.select_medical_record = index
        },
        td_change(el,index,num){  // 输入病历信息后，保存病历信息
            if(num==0){
                this.patient.medical_record[index][0](0,1,el.currentTarget.innerText.trim())
                let e = el.currentTarget
                let id = e.getAttribute("id")
                this.patient.medical_record[index][id]=e.innerText.trim()
            }else if(num==1){
                let e = el.currentTarget
                let id = e.getAttribute("id")
                this.patient.medical_record[index][id]=e.innerHTML.trim()
            }
        },
        td_change1(e){  // 保存基本资料
            let el = e.currentTarget
            let id = e.currentTarget.getAttribute("id")
            this.patient[id]=el.innerText.trim()
        },
        change_other(e,index){
            if(this.submitShow){
                let el = e.currentTarget
                let id = e.currentTarget.getAttribute("id")
                if(id=="prescription"){
                    this.pop_up_id=id
                    this.pop_up_title="编辑处方"
                    this.pop_up_content=this.patient.medical_record[index][id]
                    this.isShow_pop_up=true
                }else if(id=="treatment_results"){
                    this.pop_up_id=id
                    this.pop_up_title="编辑治疗结果"
                    this.pop_up_content=this.patient.medical_record[index][id]
                    this.isShow_pop_up=true
                }
            }
        },
        pop_up_ok(){
            // if(this.pop_up_id="prescription"){
            this.patient.medical_record[this.select_medical_record][this.pop_up_id]=this.pop_up_content
            this.isShow_pop_up=false
            // }
        },
        pop_up_cancel(){
            if(this.pop_up_id="prescription"){
                // this.patient.medical_record[this.select_medical_record][this.pop_up_id]=this.pop_up_content
                // this.patient.medical_record[this.select_medical_record][this.pop_up_id]=this.patient.medical_record[this.select_medical_record][this.pop_up_id]
                this.isShow_pop_up=false
            }
        },
        check_data(data){  // 检查输入的信息是否正确
            
            for (let item in data){
                if (data[item] instanceof Array){
                    let temp = data[item]
                    for(let i in temp){
                        let ret = this.check_data(temp[i])
                        if(ret==false){
                            return false
                        }
                    }
                }
                if(this.$my_tools.check_data[item]){ 
                    
                    let msg=this.$my_tools.check_data[item](data[item])
                    if(msg){
                        this.$toast(msg)
                        this.err_msg=msg
                        this.err_msg_show=true
                        return false
                    }
                }
            }
        },
        submit(){  // 提交编辑后的信息
            if(this.check_data(this.patient)==false){
                return
            }
            // document.querySelectorAll(".edit")[0].innerText="编辑信息"
            // this.submitShow=false
            let conf = confirm("你确定要保存该编辑吗")
            if(!conf){
                console.log("取消编辑");
                return
            }
            this.button_text='编辑信息'
            this.submitShow=!this.submitShow
            let values = document.querySelectorAll(".value")
            values.forEach((item,index)=>{
                item.setAttribute("contentEditable",this.submitShow)
            })

            // 为了保险起见，还是验证下删除列表del_m_r里的病历 是否是当前病人的病历，这一步貌似可以省略
            if(this.del_m_r.length>0){  
                this.del_m_r.forEach((item,index)=>{
                    if(item.patient_id != this.patient.id){
                        this.$toast.fail("你要删除的病历不是当前病人的，请重新刷新页面试试")
                        return
                    }
                })
            }
            // 发送ajax请求，保存数据
            console.log(this.patient,"提交");
            this.$http({
                method:'post',
                url:'/ajax/api/edit_patient',
                data:{
                    patient:this.patient,
                    del_m_r:this.del_m_r
                }
            }).then(data=>{
                if(data.data=="ok"){
                    this.$toast.success("编辑成功")
                    this.$router.push('/')
                    // this.$http({
                    //     method:'post',
                    //     url:'/ajax/api/search_patient',
                    //     data:{
                    //         patient:{name:this.patient.name}
                    //     }
                    // }).then(data=>{
                    //     this.$store.state.patient = data.data
                    //     this.patient=this.$my_tools.deepClone(this.$store.state.patient[0])
                    //     // if(this.$route.path=="/add_patient"){
                    //     //     this.$router.push("/patientInfo")
                    //     // }
                    // })
                    
                    // let patient_index = this.$store.state.patient[Number(this.query.reques_count)].findIndex((item)=>{ return item.id===Number(this.query.patient_id)})
                    // let medical_record_index = this.$store.state.patient[Number(this.query.reques_count)][patient_index].medical_record.findIndex((item)=>{return item.id==Number(this.query.m_r_id)})
                    // this.$store.state.patient[Number(this.query.reques_count)][patient_index].medical_record[medical_record_index] = this.patient.medical_record[0]
                    // let show_list_index = this.$store.state.show_list[Number(this.query.reques_count)].medical_record.findIndex((item)=>{return item.id==Number(this.query.m_r_id)})
                    // if(this.patient.medical_record[0]){
                    //     this.$store.state.show_list[Number(this.query.reques_count)].medical_record[show_list_index] = this.patient.medical_record[0]

                    // }else{
                    //     this.$store.state.show_list[Number(this.query.reques_count)].medical_record.splice(show_list_index,0)
                    // }
                    
                    
                }else{
                    this.$toast.fail("编辑失败，发生未知错误")
                }
            })
            // let patient_index = this.$store.state.patient[Number(this.query.reques_count)].findIndex((item)=>{ return item.id===Number(this.query.patient_id)})
            // let medical_record_index = this.$store.state.patient[Number(this.query.reques_count)][patient_index].findIndex((item)=>{return item.id==Number(this.query.m_r_id)})
            // this.$store.state.patient[Number(this.query.reques_count)][patient_index].medical_record[medical_record_index] = this.patient.medical_record[0]
            // let show_list_index = this.$store.state.show_list[Number(this.query.reques_count)].medical_record_list.findIndex((item)=>{return item.id==Number(this.query.m_r_id)})
            // this.$store.state.show_list[Number(this.query.reques_count)].medical_record_list[show_list_index] = this.patient.medical_record[0]
            
            // this.$store.state.patient[0]=this.$my_tools.deepClone(this.patient)
        },
        // 这个是更新数据的，不要删，在 components/home/homeBase.vue 里调用
        update_patient(){

            this.patient_list = this.$my_tools.deepClone(this.$store.state.patient[Number(this.query.reques_count)])
            this.patient=this.patient_list.find((item)=>{ return item.id===Number(this.query.patient_id)})
            let id = Number(this.query.m_r_id);
            this.patient.medical_record=[this.patient.medical_record.find((item)=>{return item.id==id})];

            this.del_m_r=[]  // 当重新查询数据的时候，初始化删除列表del_m_r
        },
    },
    computed:{
    },
    mounted(){
        this.query = this.$route.query
        this.select_medical_record=0
        this.patient_list = this.$my_tools.deepClone(this.$store.state.patient[Number(this.query.reques_count)])
        this.patient=this.patient_list.find((item)=>{ return item.id===Number(this.query.patient_id)})
        let id = Number(this.query.m_r_id);
        this.patient.medical_record=[this.patient.medical_record.find((item)=>{return item.id==id})];
        
    },
    beforeUnmount(){
        // this.$store.state.patient[0] = this.patient
    }
}
</script>

<style lang='scss' scoped>
.container{
    height: 80%;
    position: relative;
}
.patient-info{
    border: 1px solid #ccc;
    // width: 90%;
    height: 100%;
    margin-top: 5px;
    padding: 5px;
    overflow: auto;
    display: flex;
    align-items: flex-start;
    // position: relative;
    // 表格样式
    
    table,tr{
        flex:0 0 auto;
        td{
            padding: 8px;
            border: 1px solid #aaa;
            vertical-align: middle;
        }
        .value{
            width: 200px;
            word-break: break-all;
        }
        .key{
            font-weight: bolder;
            width: 100px;
        }
        .medical_record{
            padding: 3px;
            tr,td{
                // padding: 10px;
                border:none;
                font-size: 13px;
            }
            .value{
                border-bottom: 1px solid #aaa;
                width:300px;
            }
            [small]{
                width: 130px;
            }
            textarea.value{
                // flex: 1;
                // background-color: #f1f1f1;
                // border: none;
                // resize:vertical;
                margin: 0px 10px;
                padding: 5px;
                resize: none;
                height: 50px;
                width: calc(100% - 30px);
            }
        }
        
    }
    .pop_up{
        width: 80%;
        height: 100%;
        padding: 10px;
        border: 1px solid black;
        border-radius: 10px;
        background-color: #f1f1f1;
        position:absolute;
        // top:;
        display: flex;
        flex-direction: column;
        .header{
            margin: 0 10px;
            // width: 80%;
            display: flex;
            justify-content: space-between;
        }
        .close{
            cursor: default;
        }
        .close:hover{
            background-color: rgb(84, 84, 253);
            color: white;
        }
        .ipt{
            width: 60%;
        }
        textarea{
            // flex: 1;
            // margin: 10px auto;
            resize: none;
            height: 80%;
            width: 80%;
        }
        .ok{
            width: 60px;
            height: 30px;
            margin-left:100px ;
            cursor: default;
            background-color: rgb(243, 105, 128);
            color: white;
            border-radius: 5px;
            text-align: center;
            line-height: 30px;
        }
    }
    
    .first_col{
        tr,td{
            border: none;
        }
    }
    .button{
        display: flex;
        margin-left: 10px;
        flex-direction: column;
        // position:absolute;
        // top: 15px;
        // right: 5px;
        // flex:1;
        button{
            margin-bottom: 10px;
            width: 80px;
            // text-align:ce;
            // background-color: rgb(245, 159, 102);
            // color: rgb(247, 238, 201);
        }
    }
    .center{
        font-weight: bolder;
        // text-align: center;
    }
    .spare{
        font-size: 20px;
        font-weight: bolder;
        margin: 50px auto;
    }
    .select{
        background-color: #f1f1f1;
    }
}
</style>